package com.sockect3d;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sockect3d.data.ControlGesture;
import com.sockect3d.data.DLInfo_da;
import com.sockect3d.data.DList_da;
import com.sockect3d.data.DataUtils;
import com.sockect3d.data.ImagWH;
import com.sockect3d.data.NetProtocol;
import com.sockect3d.data.Vidio_can;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import static android.os.Build.CPU_ABI;

/**
 * Created by ming.zhang on 2016/9/19.
 */
public class Vedio_Activity extends AppCompatActivity implements View.OnClickListener {
    /* 服务器地址 */
    private final String SERVER_HOST_IP = "10.0.5.37";

    /* 服务器端口 */
    private final int SERVER_HOST_PORT = 5002;
    private int id;
    private Button netC;
    private OpenSer openser;
    private ImageView videoImage;
    byte[] Imagdata;
    private Bitmap videoBit;
    private ReadThreade readThread1;


    //创建对象
    com.hermes.android.netengine_clinet.MainActivity ma = new com.hermes.android.netengine_clinet.MainActivity();



    byte[] tok = null;
    byte[] mPixel;
    private Boolean isflg = true;
    private Boolean isCotrl = false;
    private Boolean isCnected = false;
    private Boolean isRnected = false;
    private boolean isShowing;
    Matrix matrix = new Matrix();
    Queue<byte[]> dataList = new LinkedList<byte[]>();
    playThread playthd = new playThread();
    //控制

    private String USER_ID = "user_id";
    private ControlGesture controlGesture = new ControlGesture();
    int height;

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 0:
                    setJepagImage(Imagdata);
                    break;
                case 1:
                    setImage(videoBit);
                    break;

                default:
                    break;
            }
        }
    };
    long x;
    File file = new File(Environment.getExternalStorageDirectory()+"/24City/Budget/"+"TestFude.h264");
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉信息栏
        super.onCreate(savedInstanceState);
        height = 360;
        if(height%2 != 0){
            height = height+1;
        }
        Random rd1 = new Random();
        int n = rd1.nextInt(1000000000);
        x = n;
        byte[] token = DataUtils.longToBytes(x);
        tok = token;
        setContentView(R.layout.vedio_lyout);
        matrix.postScale(1, -1);//上下翻转

        Intent intent = getIntent();
//        id = 751;
        id = getIntent().getIntExtra("id",751);
        init();
        initView();
    }
    int flag_3d = -1;
    public void init(){
        videoImage = (ImageView) findViewById(R.id.imgVideoView);
    }
    public void initView() {
        videoImage.setOnTouchListener(new ctr_lef_lishener());
        //初始化请求模型的宽高（分辨率）

        flag_3d = ma.libAvDecodecInit(500,height);
        playVidio();
    }
    public void ctlShowVideod(){
        ArrayList<DList_da> dList = new ArrayList<DList_da>();
        dList.add(new DList_da(id));
        DLInfo_da DLInfo = new DLInfo_da(1, 4,-1, dList);
        ImagWH wh = new ImagWH();
        wh.setImageWidth(500);
        wh.setImageHeight(height);
        Vidio_can v_id = new Vidio_can(456, 2, 1,2000, wh, DLInfo);
        Gson gson = new Gson();
        String requestJson = gson.toJson(v_id);


        //创建socket连接的地址及端口号
        k = ma.libClientInit("182.150.6.136",5002);
        if(k > 0){
            m = ma.lib3DCreate(k,x,requestJson);
            if(m==0){
//                Toast.makeText(con,"m==="+m,Toast.LENGTH_SHORT).show();
                Log.d("-------","m=="+m);
                ma.libSendMsg(k,x, NetProtocol.HMS_COMMUNICATION_PROTOCOL_OPERATOR_TYPE_CTRLTD, NetProtocol.ND_IMAGE_PLAY,null,0);
            }
        }
    }


    long k = -1;
    long m = -1;
    public void playVidio(){
        openser = new OpenSer();
        openser.start();

    }
    protected void setImage(Bitmap data)
    {
        if(data!=null){
            videoImage.setImageBitmap(Bitmap.createBitmap(data, 0, 0, data.getWidth(), data.getHeight(), matrix, true));
//            videoImage.setImageBitmap(data);
        }

    }

    protected void setJepagImage(byte[] data)
    {
        if (Imagdata != null
                && Imagdata.length > 0)
        {
            if(BitmapFactory.decodeByteArray(data, 0,
                    data.length, null)!=null){

                Bitmap bm = BitmapFactory.decodeByteArray(data, 0,
                        data.length, null);
                // 根据旋转角度，生成旋转矩阵

                if(bm!=null){
                    videoImage.setImageBitmap(Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true));
                }
            }
        }
    }

    @Override
    public void onClick(View v) {

    }

    public class OpenSer extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                isShowing = true;
                ctlShowVideod();
                if (readThread1 == null)
                {
                    readThread1 = new ReadThreade();
                    readThread1.start();
                    playthd.start();
                }

                // ctlSetTypeImage();

                //
            } catch (Exception e)
            {
                e.printStackTrace();
                // videoViewActivity.showMessage("服务失败", "三维服务不可用");
                showToast("三维服务不可用");
            }
        }
    }
    public void showToast(String msg)
    {
        Looper.prepare();
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
        Looper.loop();
    }
    Integer pHdr_Type = new Integer(0);
    Integer pHdr_Code = new Integer(0);
    Integer pInt_Len = new Integer(0);
    byte[] codeData;
    FileOutputStream fos;
    int klj = 0;
    Boolean flag = true;
    int removeK = 3;
    private class ReadThreade extends Thread
    {
        @Override
        public void run()
        {
            if(m == 0){

                while (isflg)
                {
                    try
                    {
                        while (isShowing)
                        {
                            isCotrl = true;
                            pInt_Len = 500*height*3;
                            mPixel = ma.libRecvMsg(k,null,pHdr_Type,pHdr_Code,pInt_Len,true);

                            Log.d("=========","kl-->0"+"pHdr_Type-->"+pHdr_Type+"pHdr_Code-->"+pHdr_Code+"pInt_Len-->"+pInt_Len+"==="+mPixel.length);

                            if(pHdr_Code == NetProtocol.ND_H264){
                                Log.d("========","111");
                                if(pInt_Len>0){
                                    if(dataList.size() >= 35){
                                        switch (removeK){
                                            case 1:
                                                Log.d("移除一帧","移除第"+removeK+"帧"+dataList.peek());
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 5;
                                                break;
                                            case 5:
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 9;
                                                break;
                                            case 9:
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 14;
                                                break;
                                            case 14:
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 19;
                                                break;
                                            case 19:
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 23;
                                                break;
                                            case 23:
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 27;
                                                break;
                                            case 27:
                                                dataList.remove(removeK);
                                                Log.d("移除一帧","移除第"+removeK+"帧");
                                                removeK = 1;
                                                break;
                                            default:
                                                removeK = 1;
                                                break;
                                        }
                                    }
                                    dataList.offer(mPixel);
                                }
                            }else if(pHdr_Code == NetProtocol.ND_JPEG){

                                if (pInt_Len > 0)
                                {

                                    Imagdata = mPixel;
                                    Message msg = new Message();
                                    msg.what = 0;
//											handler.sendMessageDelayed(handler.obtainMessage(0), 500);
                                    handler.sendMessage(msg);

                                }
                            }
                        }

                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }


        }
    }

    /**
     * 解码h264数据
     */
    byte[] pho= null;
    class playThread extends Thread{
        public void run(){
            while(true){
                if(dataList.size()>0){
                    Log.d("*******",dataList.size()+"");
                    pho = dataList.poll();
                    if (pho != null
                            && pho.length > 0)
                    {// 一帧数据收到解码
                        if(flag_3d == 0){
                            codeData = ma.libAvDecodecData(pho,pho.length);
                            if(codeData != null && codeData.length>0){
                                videoBit = BitmapFactory.decodeByteArray(codeData,0,codeData.length);
                                Message msg = new Message();
                                msg.what = 1;
                                handler.sendMessage(msg);
                            }else{
                            }

                        }else{
                        }
                    }else{
                    }

                }

                try {
                    this.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
    public void closeTh()
    {
        openser.interrupt();
        openser = null;
    }

    class cotrAll extends TimerTask
    {

        @Override
        public void run()
        {
            // TODO Auto-generated method stub
            long operatorCode = NetProtocol.ND_TOUCHCTRL_MOVE;
            // long operatorCode = NetProtocol.ND_TOUCHCTRL_MOVE;
            controlGesture.setScal(1.0f);
            controlGesture.setMoveX(MoveX);
            controlGesture.setMoveY(MoveY);
            controlGesture.setRotateX(rotateX/500.0f);
            controlGesture.setRotateY(-rotateY/500.0f);
            Gson gson = new Gson();
            String requestJson = gson.toJson(controlGesture);
            Log.d("&&&&&&","发送操作");
            Log.d("&&&&&&",requestJson);
            ma.libSendMsg(k,x, NetProtocol.HMS_COMMUNICATION_PROTOCOL_OPERATOR_TYPE_CTRLTD, NetProtocol.ND_TOUCHCTRL_MOVE,requestJson.getBytes(),requestJson.getBytes().length);

        }

    }
    private Timer ctrtimer;
    private cotrAll cotrall;
    private int ctr_x;
    private int ctr_y;
    private int ctr_x_0;
    private int ctr_y_0;
    private ImageView ctr_lf;private float rotateX;
    private float rotateY;
    private float MoveX;
    private float MoveY;


    float x0;
    float y0;

    float x1;
    float y1;

    MyThread myThread;
    class ctr_lef_lishener implements View.OnTouchListener{


        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int v_id = view.getId();
            if(v_id== R.id.imgVideoView){
                if(isCotrl){
                    if (event.getPointerCount() == 1)
                    {
                        switch (event.getActionMasked())
                        {
                            case MotionEvent.ACTION_DOWN:
                                x0 = event.getX(0);
                                y0 = event.getY(0);
                                if(!isCnected&&!isRnected){
                                    isCnected = true;
                                    ctrtimer = new Timer();
                                    if(cotrall==null){
                                        cotrall = new cotrAll();
                                        ctrtimer.schedule(cotrall, 0, 40);
                                    }else{
                                        ctrtimer.schedule(cotrall, 0, 40);
                                    }
                                }
                                break;
                            case MotionEvent.ACTION_MOVE:
                                Log.d("-----","旋转跳跃");

                                if(Math.abs(event.getX(0)-x0)>2&&Math.abs(event.getY(0) - y0)>2){
                                    rotateX = event.getX(0)-x0;
                                    rotateY = event.getY(0) - y0;
                                    if(rotateX>100* DensityUtil.getDisplayDensity()){
                                        rotateX = 100* DensityUtil.getDisplayDensity();
                                    }else if(rotateX<-(100* DensityUtil.getDisplayDensity())){
                                        rotateX = -(100* DensityUtil.getDisplayDensity());
                                    }
                                    if(rotateY>100* DensityUtil.getDisplayDensity()){
                                        rotateY = 100* DensityUtil.getDisplayDensity();
                                    }else if(rotateY<-(100* DensityUtil.getDisplayDensity())){
                                        rotateY = -(100* DensityUtil.getDisplayDensity());
                                    }
                                }


                                break;
                            case MotionEvent.ACTION_UP:
                                MoveX = 0.0f;
                                MoveY = 0.0f;
                                rotateX = 0.0f;
                                rotateY = 0.0f;
                                Log.d("--------","sqdhgqksjbdu"+"");
//                                ctr_lf.setImageResource(R.drawable.cotlo_back);
                                if(!isRnected){
                                    if(ctrtimer!=null){
                                        ctrtimer.cancel();
                                        ctrtimer = null;
                                        cotrall = null;
                                    }
                                }

                                new Thread(new Runnable(){
                                    @Override
                                    public void run() {
                                        ctrfw();
                                    }
                                }).start();
                                isCnected = false;
                                break;
                            default:
                                break;
                        }
                    }else if(event.getPointerCount() == 2){

                        switch (event.getActionMasked()){

                            case MotionEvent.ACTION_POINTER_DOWN:
                                x0 = event.getX(0);
                                x1 = event.getX(1);
                                y0 = event.getY(0);
                                y1 = event.getY(1);
//                                if(!isCnected&&!isRnected){
//                                    isCnected = true;
//                                    ctrtimer = new Timer();
//                                    if(cotrall==null){
//                                        cotrall = new cotrAll();
//                                        ctrtimer.schedule(cotrall, 0, 40);
//                                    }else{
//                                        ctrtimer.schedule(cotrall, 0, 40);
//                                    }
//                                }
                                break;
                            case MotionEvent.ACTION_MOVE:
                                ctr_x = (int)(event.getX(0)-x0);
                                ctr_x_0 = (int)(event.getX(1)-x1);
                                ctr_y_0 = (int)(event.getY(1)-y1);
                                ctr_y = (int)(event.getY(0)-y0);
                                if(ctr_x!=0&&ctr_y!=0&&ctr_x_0!=0&&ctr_y_0!=0){
                                    if(ctr_x<0 && ctr_x_0<0 && (Math.abs(ctr_x)>Math.abs(ctr_y)&&Math.abs(ctr_x_0)>Math.abs(ctr_y_0))){
                                        MoveX = 0.0f;
                                        MoveY = 0.6f;
                                        Log.d("---","向左");
                                    }else if(ctr_x>0&&ctr_x_0>0 && (Math.abs(ctr_x)>Math.abs(ctr_y)&&Math.abs(ctr_x_0)>Math.abs(ctr_y_0))){
                                        MoveX = 0.0f;
                                        MoveY = -0.6f;
                                        Log.d("---","向右");
                                    }else if(ctr_y > 0 && ctr_y_0 > 0 && (Math.abs(ctr_x)<Math.abs(ctr_y)&&Math.abs(ctr_x_0)<Math.abs(ctr_y_0))){
                                        MoveX = 0.6f;
                                        MoveY = 0.0f;
                                        Log.d("---","向上");
                                    }else if(ctr_y < 0 && ctr_y_0 < 0 && (Math.abs(ctr_x)<Math.abs(ctr_y)&&Math.abs(ctr_x_0)<Math.abs(ctr_y_0))){
                                        MoveX = -0.6f;
                                        MoveY = 0.0f;
                                        Log.d("---","向下");
                                    }
                                }


                                break;
                        }
                    }
                }
            }
            return true;
        }
    }
    private static class MyThread extends Thread {
        WeakReference<Vedio_Activity> mThreadActivityRef;

        public MyThread(Vedio_Activity activity) {
            mThreadActivityRef = new WeakReference<Vedio_Activity>(
                    activity);
        }

        @Override
        public void run() {
            super.run();
            if (mThreadActivityRef == null)
                return;
            if (mThreadActivityRef.get() != null)
                mThreadActivityRef.get().ctrfw();
            // dosomthing
        }
    }

    public void ctrfw(){
        // TODO Auto-generated method stub
        long operatorCode = NetProtocol.ND_TOUCHCTRL_MOVE;
        // long operatorCode = NetProtocol.ND_TOUCHCTRL_MOVE;
        controlGesture.setScal(1.0f);
        controlGesture.setMoveX(0.0f);
        controlGesture.setMoveY(0.0f);
        controlGesture.setRotateX(rotateX/500.0f);
        controlGesture.setRotateY(-rotateY/500.0f);
        Gson gson = new Gson();
        String requestJson = gson.toJson(controlGesture);
        ma.libSendMsg(k,x, NetProtocol.HMS_COMMUNICATION_PROTOCOL_OPERATOR_TYPE_CTRLTD, NetProtocol.ND_TOUCHCTRL_MOVE,requestJson.getBytes(),requestJson.getBytes().length);
    }

    public void onDestroy()
    {

        super.onDestroy();
        try
        {

            if(k == 0){
                ma.libClose(k);
            }
            ma.libAvDecodecDestroy();
            isflg = false;
            isCotrl = false;
            isCnected = false;
            isRnected = false;
            readThread1.interrupt();
            readThread1 = null;
            closeTh();
            // isShowing = false;
        } catch (Exception e)
        {
            handler.removeCallbacks(readThread1);
        }
    }
    public static void startActivity(Context context, String id){
        if (TextUtils.equals(CPU_ABI , "x86")){
            Utils.showToast(context,"您的机型不支持3D漫游系统");
        }else{
            context.startActivity(new Intent(context,Vedio_Activity.class).putExtra("id", Utils.toInt(id)));
        }

    }
}
